<template>
  <el-dialog
    v-model="visible"
    title="选择优惠券"
    top="100px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="prods-select-body">
      <el-table
        ref="couponTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        border
        header-cell-class-name="table-header"
        row-class-name="table-row"
        style="width: 100%"
        @selection-change="selectChangeHandle"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-radio
                v-model="singleSelectCouponId"
                :label="scope.row.couponId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          prop="couponName"
          header-align="center"
          align="center"
          :label="$t('marketing.couponName')"
        />
        <el-table-column
          prop="getWay"
          header-align="center"
          align="center"
          :label="$t('coupon.couponType')"
        />
        <el-table-column
          prop="limitNum"
          header-align="center"
          align="center"
          :label="$t('user.couponUpperLimit')"
        />
      </el-table>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="justify-content: flex-end;"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <template #footer>
      <span>
        <span
          class="default-btn"
          @click="visible = false"
        >{{ $t("remindPop.cancel") }}</span>
        <span
          class="default-btn primary-btn"
          @click="submitProds()"
        >{{ $t("remindPop.confirm") }}</span>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

const emit = defineEmits(['refreshSelectCouponList', 'refreshSelectCouponList', 'refreshSelectCouponList'])

const singleSelectCouponId = ref(0)
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  // 获取方式 null:默认（客户领取+平台发放） 0=客户领取 1=平台发放
  getWay: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/admin/coupon/list',
    type: String
  }
})

onActivated(() => {
  getDataList()
})

// 获取数据列表
const dataListLoading = ref(false)
const dataListSelections = ref([])

const visible = ref(false)
const selectCoupons = ref([])
const init = (isSelectCoupons) => {
  selectCoupons.value = isSelectCoupons
  visible.value = true
  dataListLoading.value = true
  selectCoupons.value = isSelectCoupons
  if (selectCoupons.value) {
    selectCoupons.value.forEach(row => {
      dataListSelections.value.push(row)
    })
  }
  getDataList()
}
const dataForm = {
  product: ''
}
const dataList = ref([])
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const couponTableRef = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: page.value.currentPage,
          size: page.value.pageSize
        },
        {
          prodName: dataForm.prodName,
          getWay: props.getWay
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    dataList.value.forEach(item => {
      // 平台投放 / 用户领取
      item.getWay = item.getWay === 1 ? $t('coupon.platformDistribution') : $t('coupon.userClaim')
    })
    page.value.total = data.total
    dataListLoading.value = false
    if (selectCoupons.value) {
      nextTick(() => {
        selectCoupons.value.forEach(row => {
          const index = dataList.value.findIndex((couponItem) => couponItem.couponId === row.couponId)
          couponTableRef.value.toggleRowSelection(dataList.value[index])
        })
      })
    }
  })
}
// 每页数
const onPageSizeChange = (val) => {
  page.value.pageSize = val
  page.value.currentPage = 1
  getDataList()
}
// 当前页
const onPageChange = (val) => {
  page.value.currentPage = val
  getDataList()
}
// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections.value = [row]
}
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedCoupon) => {
      if (!selectedCoupon) {
        dataListSelections.value = []
        return false
      }
      return selectedCoupon.couponId === tableItem.couponId
    })
    const dataSelectedProdIndex = dataListSelections.value.findIndex((dataSelectedCoupon) => dataSelectedCoupon.couponId === tableItem.couponId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.value.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.value.splice(dataSelectedProdIndex, 1)
    }
  })
}
// 确定事件
const submitProds = () => {
  // 商品单选的情况
  if (props.isSingle) {
    dataListSelections.value.length && emit('refreshSelectCouponList', dataListSelections.value[0])
    dataListSelections.value = []
    visible.value = false
    return
  }
  // 多选
  const coupons = []
  if (dataListSelections.value.length < 1) {
    emit('refreshSelectCouponList', [])
  } else {
    dataListSelections.value.forEach(item => {
      const couponIndex = coupons.findIndex((coupon) => coupon.couponId === item.couponId)
      if (couponIndex === -1) {
        coupons.push({ couponId: item.couponId, couponName: item.couponName, subTitle: item.subTitle, limitNum: item.limitNum })
      }
    })
    emit('refreshSelectCouponList', coupons)
  }

  dataListSelections.value = []
  visible.value = false
}
defineExpose({ init })
</script>
<style scoped>
.prods-select-body {
  height: 600px;
  overflow: auto;
  border-top: 1px solid #eeeeee;
  border-right: 1px solid #eeeeee;
  border-bottom: 1px solid #eeeeee;
}
</style>
